#include "comm.hpp"

int main()
{
    // 1.创建公共的key
    key_t key = ftok(FILENAME, PROJ_ID);
    if (key == -1)
    {
        Log("creat key fail", Error) << "client_key: " << key << std::endl;
        return 1;
    }
    Log("creat key success", Debug) << "client_key: " << key << std::endl;

    // 2.打开共享内存
    int shmid = shmget(key, SHM_SIZE, 0);
    if (shmid == -1)
    {
        Log("creat shmid fail", Error) << "client_shmid: " << shmid << std::endl;
        return 2;
    }
    Log("creat shmid success", Debug) << "client_shmid: " << shmid << std::endl;

    // 3.将共享内存挂到地址空间
    char* shmem = (char*)shmat(shmid, nullptr, 0);
    if (shmem == nullptr)
    {
        Log("creat shared memory fail", Error) << "client_shmid: " << shmid << std::endl;
        return 3;
    }
    Log("creat shared memory success", Debug) << "client_shmid: " << shmid << std::endl;

    // 4.使用共享内存
    int fd = OpenFile(O_WRONLY);
    while (true)
    {
        ssize_t num = read(0, shmem, SHM_SIZE - 1);
        Singal(fd);
        if (num > 0)
        {
            shmem[num - 1] = '\0';
            if (strcmp(shmem, "quit") == 0)
                break;
        }
    }
    close(fd);

    // 5.将共享内存和进程去关联
    int n = shmdt(shmem);
    assert(n != -1);
    (void)n;
    Log("unlink shared memory success", Debug) << "client_shmid: " << shmid << std::endl;
    
    return 0;
}